package platformlog_logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlx"

	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryAuditLogLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewQueryAuditLogLogic 查询审计日志
func NewQueryAuditLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryAuditLogLogic {
	return &QueryAuditLogLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QueryAuditLogLogic) QueryAuditLog(req *types.QueryAuditLogRequest) (resp *types.QueryAuditLogResponse, err error) {
	// 构建 SQL 查询语句和条件
	query := `SELECT id, client_ip, user_id, username, operation_type, request_uri, 
				request_body, response_body, status_code, user_agent,
				server_node, start_time, end_time, duration 
			FROM audit_log WHERE 1=1`
	var args []interface{}

	// 动态拼接查询条件
	if req.ClientIP != "" {
		query += " AND client_ip = ?"
		args = append(args, req.ClientIP)
	}
	if req.Username != "" {
		query += " AND username = ?"
		args = append(args, req.Username)
	}
	if req.OperationType != "" {
		query += " AND operation_type = ?"
		args = append(args, req.OperationType)
	}
	if req.StatusCode != 0 {
		query += " AND status_code = ?"
		args = append(args, req.StatusCode)
	}
	if req.UserAgent != "" {
		query += " AND user_agent LIKE ?"
		args = append(args, "%"+req.UserAgent+"%")
	}
	if req.ServerNode != "" {
		query += " AND server_node = ?"
		args = append(args, req.ServerNode)
	}
	if req.StartTime != "" {
		query += " AND start_time >= ?"
		args = append(args, req.StartTime)
	}

	// 排序和限制
	query += " ORDER BY start_time DESC"

	// 执行查询
	var logs []types.AuditLog
	err = l.svcCtx.Conn.QueryRows(&logs, query, args...)
	if err != nil {
		if errors.Is(err, sqlx.ErrNotFound) {
			// 如果没有找到数据，返回空结果
			return &types.QueryAuditLogResponse{
				Code:    200,
				Message: "查询成功，无数据",
				Data:    []types.AuditLog{},
			}, nil
		}
		// 记录错误日志
		l.Errorf("查询审计日志失败: %v, SQL: %s, Args: %v", err, query, args)
		return &types.QueryAuditLogResponse{
			Code:    500,
			Message: fmt.Sprintf("查询审计日志失败: %v", err),
		}, err
	}

	return &types.QueryAuditLogResponse{
		Code:    200,
		Message: "查询成功",
		Data:    logs,
	}, nil
}
